package org.csu.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.demo.common.CommonResponse;
import org.csu.demo.domain.*;
import org.csu.demo.persistence.LineItemMapper;
import org.csu.demo.persistence.OrderStatusMapper;
import org.csu.demo.persistence.OrdersMapper;
import org.csu.demo.persistence.SequenceMapper;
import org.csu.demo.service.CartService;
import org.csu.demo.service.OrderService;
import org.csu.demo.service.OrderStatusService;
import org.csu.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.*;

@Repository("orderService")
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    OrderStatusMapper orderStatusMapper;
    @Autowired
    LineItemMapper lineItemMapper;
    @Autowired
    UserService userService;
    @Autowired
    CartService cartService;
    @Autowired
    private SequenceMapper sequenceMapper;
    @Autowired
    private OrderStatusService orderStatusService;

    private List<LineItemVo> lineItemVos = new ArrayList<>();
    @Autowired
    private CatalogServiceImpl catalogService;

    //将订单插入购物车
    public void insertOrder(OrderVo orderVo) {
        //更新inventory中的数量
        for (int i = 0; i < orderVo.getLineItemVos().size(); i++) {
            LineItemVo lineItemVo = orderVo.getLineItemVos().get(i);
            String itemId = lineItemVo.getLineItem().getItemId();
            Integer increment = new Integer(lineItemVo.getLineItem().getQuantity());
            Map<String, Object> param = new HashMap<String, Object>(2);
            param.put("itemId", itemId);
            param.put("increment", increment);
            catalogService.updateInventoryQuantity(param);
        }
        ordersMapper.insert(orderVo.getOrders());
        for (int i = 0; i < orderVo.getLineItemVos().size(); i++) {
            LineItemVo lineItemVo =  orderVo.getLineItemVos().get(i);
            lineItemMapper.insert(lineItemVo.getLineItem());
            orderStatusMapper.insert(lineItemVo.getOrderStatus());
        }
    }

    public void clearlineItemVos(){
        lineItemVos.clear();
    }

    //根据数据库中的购物车列表生成订单
    public OrderVo initOrder(String username){
        //清除
        //lineItemVos.clear();
        OrderVo orderVo = new OrderVo();
        User user = null;
        if(userService.isUsernameExist(username).getMessage().equals("Not Exist")){
            user = userService.getUserByUsername("demo").getData();
        }else{
            user = userService.getUserByUsername(username).getData();
        }
        Orders order = new Orders();
        Account account = user.getAccount();
        CartVo cartVo = cartService.findAllCarts(username).getData();
        order.setOrderId(getNextId("ordernum"));
        order.setUserId(username); ;
        //修改方案
        java.util.Date utilDate = new Date();
        order.setOrderDate(utilDate) ;
        order.setShipToFirstName(account.getFirstname()) ;
        order.setShipToLastName(account.getLastname()) ;
        order.setShipAddress1(account.getAddress1()) ;
        order.setShipAddress2(account.getAddress2()) ;
        order.setShipCity(account.getCity()) ;
        order.setShipState(account.getState()) ;
        order.setShipZip(account.getZip()) ;
        order.setShipCountry(account.getCountry()) ;
        order.setBillToFirstName(account.getFirstname()) ;
        order.setBillToLastName(account.getLastname()) ;
        order.setBillAddress1(account.getAddress1()) ;
        order.setBillAddress2(account.getAddress2()) ;
        order.setBillCity(account.getCity()) ;
        order.setBillState(account.getState()) ;
        order.setBillZip(account.getZip()) ;
        order.setBillCountry(account.getCountry()) ;
        order.setTotalPrice(cartVo.getTotalPrice()) ;
        order.setCreditCard("999 9999 9999 9999") ;
        order.setExpireDate("12/03"); ;
        order.setCardType("Visa") ;
        order.setCourier("UPS") ;
        order.setLocale("CA") ;
        orderVo.setOrders(order);
        Iterator<Cart> i = cartVo.getCarts().iterator();
        while (i.hasNext()) {
            Cart cartItem = i.next();
            this.addLineItem(cartItem, order.getOrderId());
        }
        orderVo.setLineItemVos(this.lineItemVos);
        return orderVo;
    }
    //获取用户的订单信息
    public CommonResponse<OrderVo> getOrderVo(int orderId){
        OrderVo orderVo = new OrderVo();
        Orders orders = ordersMapper.selectById(orderId);
        orderVo.setLineItemVos(this.getLineItemVosByOrderId(orderId));
        orderVo.setOrders(orders);
        return CommonResponse.createForSuccess(orderVo);
    }

    public List<LineItemVo> getLineItemVosByOrderId(int orderId){
        List<LineItemVo> lineItemVoList = new ArrayList<>();
        QueryWrapper<LineItem> lineItemQueryWrapper = new QueryWrapper<>();
        lineItemQueryWrapper.eq("orderid", orderId);
        List<LineItem> lineItems = lineItemMapper.selectList(lineItemQueryWrapper);
        OrderStatus orderStatus = null;
        for(LineItem lineItem : lineItems){
            LineItemVo lineItemVo = new LineItemVo();
            int lineNum = lineItem.getLineNumber();
            orderStatus = orderStatusService.getOrderStatusByCompositeKey(orderId,lineNum);
            lineItemVo.setOrderStatus(orderStatus);
            lineItemVo.setLineItem(lineItem);
            lineItemVoList.add(lineItemVo);
        }
        return lineItemVoList;
    }

    //更新提交的订单信息
    public CommonResponse<OrderVo> updateOrder(Orders orders){
        ordersMapper.updateById(orders);
        return this.getOrderVo(orders.getOrderId());
    }

    //获取用户的所有订单
    public CommonResponse<List<OrderDTO>> getAllOrderId(String username){
        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
        ordersQueryWrapper.eq("userid", username);
        List<Orders> orders = ordersMapper.selectList(ordersQueryWrapper);
        List<OrderDTO> orderDTOList = new ArrayList<>();
        for(Orders order : orders){
            OrderDTO orderDTO = new OrderDTO(order);
            orderDTOList.add(orderDTO);
        }
        return CommonResponse.createForSuccess(orderDTOList);
    }

    public void addLineItem(Cart cartItem,int orderId) {
        LineItemVo lineItemVo = new LineItemVo(lineItemVos.size() + 1, cartItem , orderId);
        addLineItem(lineItemVo);
    }

    public void addLineItem(LineItemVo lineItemVo) {
        lineItemVos.add(lineItemVo);
    }


    public int getNextId(String name) {
        Sequence sequence = sequenceMapper.selectById(name);
        if (sequence == null) {
            throw new RuntimeException("Error: A null sequence was returned from the database (could not get next " + name
                    + " sequence).");
        }
        Sequence parameterObject = new Sequence(name, sequence.getNextId() + 1);
        sequenceMapper.updateSequenceQty(parameterObject);
        return sequence.getNextId();
    }
}
